import React ,{ useState ,useEffect }from 'react'
import { useHistory } from 'umi';
import moment from 'moment';

import type { ColumnsType } from 'antd/es/table';
import { Button ,Radio} from 'antd'
import SearchForm from '@/components/SearchForm';
import CustomTable from '@/components/Table';
import { getMessageCount, getMessageList, } from '@/service/personal/messageLists'

import { messageTypeEnum, typeEnum} from './enum'


const formItemLayout = {
  labelCol: { flex: '80px' },
  wrapperCol: { flex: '1' },
};


export default function MessageLists () {

  const [total, setTotal] = useState();
  const [params, setParams] = useState<any>({
    current: 1,
    pageSize: 10,
  });
  const [tableList, setTableList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [messageCount, setMessageCount] = useState<any>({})
  const [keys, setKeys] = useState('0')
  const [formData, setFormData] = useState({})

  const history = useHistory()

  useEffect(()=>{
    getMessageCount({}).then(res=>{
      if(res?.data){
        setMessageCount(res.data)
      }
    })
  },[])

  const formItems: any[] = [
    {
      type: 'group',
      key: 'group1',
      groupItems: [
        {
          type: 'input',
          label: '消息内容',
          name: 'messageContent',
          key: 'messageContent',
        },
        {
          type: 'input',
          label: '消息类型',
          name: 'messageType',
          key: 'messageType',
        },
        {
          type: 'dateRange',
          label: '消息时间',
          name: 'messageDate',
          key: 'messageDate'
        }
      ],
    },
  ];

  const columns: ColumnsType<InitiationAPI.InitiationColumns> = [
    {
      title: '消息类型',
      dataIndex: 'messageType',
      align: 'center',
      render: (text : string) => <span>{messageTypeEnum[text]  || '--'}</span>,
    },
    {
      title: '消息内容',
      dataIndex: 'messageContent',
      align: 'center',
    },
    {
      title: '消息状态',
      dataIndex: 'type',
      align: 'center',
      render: (text : string) => <span>{typeEnum[text]  || '--'}</span>,
    },
    {
      title: '消息时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      fixed: 'right',
      width: 250,
      render: (text, record:any) => (
        <div>
          <Button type="link" onClick={()=>{
            history.push({pathname:'/user/messageLists/details',search:`type=${record?.messageType}`,state:record})
          }}>查看</Button>
        </div>
      )
    }
  ]

  const getTabelValue = async(value:any,pagination?:any) => {
    setLoading(true)
    let values = value
    if(values?.messageDate){
      values.createTime	= moment(values.messageDate[0]).format('YYYY-MM-DD')
      values.endTime	= moment(values.messageDate[1]).format('YYYY-MM-DD')
      delete values.messageDate
    }
    setFormData(values)
    const newPagination = pagination? {
      ...pagination,
      size: pagination.pageSize
    } : {
      current: 1,
      size: params.pageSize
    }
    setParams(newPagination)
    values={
      ...values,
      ...newPagination
    }
    const  res =  await getMessageList(values)
    if(res?.data){
      setTotal(res.data?.total || 0)
      if(res.data?.records){
        setTableList(res.data?.records || [])
      }
    }
    setLoading(false)
  }

  useEffect(()=>{
    getTabelValue({...formData,type:keys})
  },[])

  const onFinish = (value: any) => {
    const values = value
    if(keys){
      values.type = keys
    }
    getTabelValue(values)
  };

  // 搜索重置
  const onReset = () => {
    getTabelValue({})
  };


  return (
      <div>
          <SearchForm
            onFinish={onFinish}
            onReset={onReset}
            formItems={formItems}
            formLayout={formItemLayout}
          />
          <div>
            <Radio.Group value={keys} onChange={(e)=>{
              setKeys(e.target.value)
              const newFormData = JSON.parse(JSON.stringify(formData))
              newFormData.type = e.target.value
              const newParams = JSON.parse(JSON.stringify(params))
              newParams.pageSize = params.size
              delete newParams.size
              getTabelValue(newFormData,newParams)
            }} style={{ marginBottom: 16 }}>
              <Radio.Button value="0">{`未读：${messageCount?.unread || 0}`}</Radio.Button>
              <Radio.Button value="1">{`已读：${messageCount?.read}` || 0}</Radio.Button>
              <Radio.Button value={null}>{`全部：${messageCount?.all}` || 0}</Radio.Button>
            </Radio.Group>
          </div>
          <CustomTable
            params={params}
            columns={columns}
            total={total}
            pagination
            callback={(pagination: any) => {
              getTabelValue(formData,pagination);
            }}
            loading={loading}
            dataSource={tableList}
          />
      </div>
  )
}
